package com.wxtwxt.ruralmall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.wxtwxt.ruralmall.auth.feign.MemberFeign;
import com.wxtwxt.ruralmall.common.constant.AuthServerConstant;
import com.wxtwxt.ruralmall.common.utils.HttpUtils;
import com.wxtwxt.ruralmall.common.utils.R;
import com.wxtwxt.ruralmall.common.vo.MemberVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Wxt
 * @create 2023-04-23 14:23
 */
@Controller
public class OAuth2Controller {
    @Resource
    private MemberFeign memberFeign;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("grant_type", "authorization_code");
        map.put("client_id", "83a624401fc06ed520b9bf16dfb36c942741611b345a5341551a6c0c548a358a");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
        map.put("client_secret", "71e67d665d23bc1fc7294ec75ee5e4abf8f0cf4915588de96fceff7b42908c53");
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", null, null, map);
        if(response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            R r = memberFeign.login(json);
            if(r.getCode() == 0) {
                MemberVo member = r.getData("member", new TypeReference<MemberVo>() {});
                session.setAttribute(AuthServerConstant.LOGIN_USER , member);
                return "redirect:http://gulimall.com";
            }
        }
        return "redirect:http://auth.gulimallc.com/login.html";
    }
}
